<template>
  <div class="app-container">
    <!-- 查询框 -->
    <div class="filter-container">
      <el-input
        v-model="pageParam.superSearchKeyWord"
        style="width: 200px;"
        placeholder="关键字查询..."
        class="filter-item"
        @keyup.enter.native="handleFilter"
        @input="handleFilter"
      />
      <el-select v-model="pageParam.model.depId" placeholder="请选择科室" @change="getListByPage()">
        <el-option label="全部" value="" />
        <el-option v-for="item in depList" :key="item.id" :label="item.depName" :value="item.id" />
      </el-select>
      <el-select v-model="pageParam.model.roleId" placeholder="请选择角色" @change="getListByPage()">
        <el-option label="全部" value="" />
        <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="list" fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
      <el-table-column class="filter-item" type="expand">
        <template slot-scope="{row}">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="邮箱">
              <span>{{ row.email }}</span>
            </el-form-item>
            <el-form-item label="住址">
              <span>{{ row.address }}</span>
            </el-form-item>
            <el-form-item label="性别">
              <span>{{ row.gender == '0' ? '女' : '男' }}</span>
            </el-form-item>
            <el-form-item label="电话号码">
              <span>{{ row.tellphone }}</span>
            </el-form-item>
            <el-form-item label="状态">
              <span>{{ row.status == '0' ? '正常' : '禁用' }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="roleName" label="角色" width="100px" />
      <el-table-column prop="depName" label="科室" width="100px" />
      <el-table-column prop="account" label="账号" width="100px" />
      <el-table-column prop="realName" label="真实姓名" width="100px" />
      <el-table-column sortable="custom" prop="age" label="年龄" width="100px" />
      <el-table-column sortable="custom" prop="creatTime" label="创建时间" />
      <el-table-column sortable="custom" prop="updateTime" label="修改时间" />

      <el-table-column label="操作" fit>
        <template slot-scope="{row,$index}">
          <el-button size="small" type="primary" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="small" v-if="row.status=='0'" type="danger" @click="handleDelete(row,1)">停用</el-button>
          <el-button size="small" v-if="row.status=='1'" type="success" @click="handleDelete(row,0)">激活</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getListByPage"
    />
    <!-- 弹窗组件 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="80px"
        style="width: 400px; margin-left:50px;"
      >

        <el-form-item label="账号" prop="account">
          <el-input v-model="temp.account" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="temp.tellphone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="temp.address" />
        </el-form-item>
        <el-form-item label="科室" prop="dep">
          <el-select v-model="temp.depId" placeholder="请选择科室">
            <el-option v-for="item in depList" :key="item.id" :label="item.depName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="temp.roleId" placeholder="请选择角色" @change="setRoleData($event)">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="temp.realName" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="temp.age" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="temp.gender" placeholder="请选择性别">
            <el-option label="男" value="1" />
            <el-option label="女" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 导入user的api
import {
  searchSomeUserByPage,
  addOneUser,
  deleteOneUserTrue,
  updateUser,
  searchSomeRoleByPage
} from '@/api/user'
// 导入组件  记得声明组件
import Pagination from '@/components/Pagination'
import {
  getAllFather
} from '@/api/department'

export default {
  components: { // 在这里声明组件
    Pagination
  },
  data() {
    return {
      depList: [],
      list: [], // 列表数据
      total: 0,
      listQuery: { // 分页 排序  查询参数
        pageNum: 1,
        pageSize: 5
      },
      fieldQuery: { // 按字段查询
        realName: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogPvVisible: false,
      pvData: [],
      temp1: {
        id: undefined,
        realName: '',
        age: undefined,
        roleId: undefined,
        roleName: '',
        account: '',
        tellphone: '',
        email: '',
        address: '',
        headPic: '',
        gender: '男'
      },
      temp: {
        id: undefined,
        realName: '',
        age: undefined,
        roleId: undefined,
        roleName: '',
        account: '',
        tellphone: '',
        email: '',
        address: '',
        headPic: '',
        gender: '男'
      },
      rules: {
        userName: [{
          required: true,
          message: '账号不能为空',
          trigger: 'blur'
        },
        {
          min: 5,
          max: 20,
          message: '长度在 5 到 20 个字符',
          trigger: 'blur'
        }
        ],
        password: [{
          required: true,
          message: '密码不能为空',
          trigger: 'blur'
        },
        {
          min: 5,
          max: 1000,
          message: '密码长度必须超过 5 个字符',
          trigger: 'blur'
        }
        ],
        realName: [{
          required: true,
          message: '真实姓名不能为空',
          trigger: 'blur'
        },
        {
          min: 1,
          max: 6,
          message: '真实姓名长度必须在1到6之间',
          trigger: 'blur'
        }
        ],
        age: [{
          required: true,
          message: '年龄不能为空',
          trigger: 'blur'
        }]
      },
      pageParam: {
        pageNum: 1,
        pageSize: 5,
        model: {
          roleId: undefined,
          depId: undefined
        },
        orderParams: [],
        superSearchKeyWord: ''
      },
      roleList: []
    }
  },
  created() {
    this.getListByPage()
    this.getAllRole()
    this.getDep()
  },
  methods: {
    getDep() {
      getAllFather().then(res => {
        this.depList = res.content
      })
    },
    sortChange(val) {
      // console.log("排序参数",val)
      const prop = val.prop
      const order = val.order === 'ascending' ? 'asc' : 'desc'
      let orderParam
      if (prop == 'creatTime') {
        orderParam = 'creat_time' + ' ' + order
      } else if (prop == 'updateTime') {
        orderParam = 'update_time' + ' ' + order
      } else {
        orderParam = prop + ' ' + order
      }
      this.pageParam.orderParams = []
      this.pageParam.orderParams.push(orderParam)
      console.log(this.pageParam.orderParams)
      this.getListByPage()
    },
    setRoleData(roleId) {
      for (const role of this.roleList) {
        if (roleId === role.id) {
          this.temp.roleId = role.id
          this.temp.roleName = role.roleName
          // console.log(role)
        }
      }
    },
    getAllRole() {
      searchSomeRoleByPage().then(res => {
        // console.log(res)
        this.roleList = res.content
      }).catch(err => {
        console.log(err)
      })
    },
    getListByPage() {
      this.pageParam.pageNum = this.listQuery.pageNum
      this.pageParam.pageSize = this.listQuery.pageSize

      console.log(this.pageParam.orderParams)

      searchSomeUserByPage(this.pageParam).then(res => {
        // console.log(res)
        this.list = res.content.list
        this.total = res.content.total
      }).catch(err => {
        console.log(err)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getListByPage()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row, status) {
      const temp = {
        id: row.id,
        status: status
      }

      deleteOneUserTrue(temp).then(() => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
        this.getListByPage()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addOneUser(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.getListByPage()
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateUser(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.getListByPage()
          })
        }
      })
    },
    resetTemp() {
      this.temp = this.temp1
    }
  }
}
</script>

<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
